/**
 * ===========================================================================
 * 版权所有 湖南免了么网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.mianle.me
 * ===========================================================================
 * 15:12 2018/6/26
 */
package com.mianle.userapi.service.task04;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * @Author: yiyuan
 * @Description:
 * @Date: Created in 15:12 2018/6/26
 */
@Component
@Slf4j
public class DynamicScheduleTaskSecond {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    //@Autowired
    //private ScheduleExport scheduleExport;

    private ScheduledFuture<?> future;


    private String cron = "";


    public String getCron() {
        return cron;
    }


    public void setCron(String cron) {
        this.cron = cron;
        stopCron();
        future = threadPoolTaskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                    // TODO Auto-generated method stub
                try {
                    //scheduleExport.scheduleTaskExport();// 异步定时生成文件
                    System.out.println("时间："+ new Date() + "Msg:定时生成文件成功");
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                    System.out.println("Error:定时生成文件错误");
                }
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // TODO Auto-generated method stub
                if ("".equals(cron) || cron == null)
                    return null;
                // 定时任务触发，可修改定时任务的执行周期
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExecDate = trigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        });
    }


    public void stopCron() {
        if (future != null) {
            //取消任务调度
            future.cancel(true);
        }
    }
}
